import {stringUtils} from "./stringUtils";
import jQuery from 'jquery';

/**
 * 获取定制播放器的配置信息
 */
export function getPlayerConfig(envConfig, code, version, file, async = false) {
    let configPath;
    if (envConfig.Online === false) {
        configPath = stringUtils.urlJoin(envConfig.ConfigPath || "configuration", file);
    } else {
        //开发环境下
        if(envConfig.RunEnvironment === 'development') {

        } else {
            if (code === undefined || version === undefined) {
                throw Error("invalid arguments");
            }
            configPath = stringUtils.urlJoin(envConfig.BasePath, 'players', code, version, file);
        }
    }

    return jQuery.ajax({
        url: configPath,
        dataType: 'json',
        method: 'GET',
        cache: false,
        async: async
    });
}

export function getScriptConfig(envConfig, scripts, configFiles) {
    let configUrls = [], defList = [], rootPath = envConfig.Online ? envConfig.BasePath : "ref";
    configFiles.forEach(file => {
        if (envConfig.Online === false) {
            configUrls.push(stringUtils.applyTemplate(file, {"ref-path-addon": rootPath}));
        } else {
            configUrls.push(stringUtils.applyTemplate(file, {"ref-path-addon": rootPath}));
        }
    });
    configUrls.forEach(url => {
        let def = jQuery.ajax({
            url: url,
            dataType: 'json',
            method: 'GET',
            cache: false,
            async: false
        });
        defList.push(def);
    });

    return jQuery.when.apply(jQuery, defList).done(function () {
        let mergeConfig = {};
        for (let index = 0, len = arguments.length; index < len; index++) {
            if (arguments[index][0] !== undefined) {
                jQuery.extend(true, mergeConfig, arguments[index][0]);
            }
        }
        scripts.forEach(script => {
            if (mergeConfig[script.name]) {
                for (let index = 0, len = mergeConfig[script.name].css.length; index < len; index++) {
                    let template = mergeConfig[script.name].css[index];
                    mergeConfig[script.name].css[index] = stringUtils.applyTemplate(template, {"ref-path-addon": rootPath})
                }
                for (let index = 0, len = mergeConfig[script.name].script.length; index < len; index++) {
                    let template = mergeConfig[script.name].script[index];
                    mergeConfig[script.name].script[index] = stringUtils.applyTemplate(template, {"ref-path-addon": rootPath})
                }
                script.css = mergeConfig[script.name].css;
                script.script = mergeConfig[script.name].script;
                script.dependencies = mergeConfig[script.name].dependencies;
            }
        });
    });
}